package com.yokead.controller.sysadmin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.CharsetUtil;
import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.yokead.common.Config;
import com.yokead.common.base.RewriteBaseControl;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by jiangzeyin on 2017/5/10.
 */
@Controller
@RequestMapping("sysadmin")
public class EditConfControl extends RewriteBaseControl {

    @RequestMapping(value = "edit_conf.html", produces = MediaType.TEXT_HTML_VALUE)
    public String edit_conf(String parent, String name) {
        parent = convertFilePath(parent);
        name = convertFilePath(name);
        String filePath = StringUtil.clearPath(String.format("%s/%s/%s", Config.Nginx.getNginxConfigPath(), parent, name));
        try {
            String context = FileUtil.readString(filePath, CharsetUtil.CHARSET_UTF_8);
            setAttribute("context", context);
            setAttribute("parent", parent);
            setAttribute("name", name);
            return "sysadmin/edit_conf";
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            setAttribute("tip", "读取错误，请联系管理员");
        }
        return "sysadmin/edit_conf";
    }

    @RequestMapping(value = "save_conf.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String edit_conf(String parent, String name, String context) {
        parent = convertFilePath(parent);
        name = convertFilePath(name);
        String filePath = StringUtil.clearPath(String.format("%s/%s/%s", Config.Nginx.getNginxConfigPath(), parent, name));
        try {
            FileUtil.writeString(context, filePath, CharsetUtil.CHARSET_UTF_8);
            reloadNginx("修改" + filePath);
            return JsonMessage.getString(200, "保存成功");
        } catch (IORuntimeException e) {
            SystemLog.ERROR().error("异常", e);
        }
        //System.out.println(context);
        return JsonMessage.getString(500, "保存失败");
    }

}
